package org.xjtu.weteam.service.Impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.ss.util.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xjtu.weteam.common.utils.TokenUtils;
import org.xjtu.weteam.common.utils.imageUtil;
import org.xjtu.weteam.mapper.UserTeamMapper;
import org.xjtu.weteam.model.domain.Team;
import org.xjtu.weteam.model.domain.User;
import org.xjtu.weteam.model.domain.UserTeam;
import org.xjtu.weteam.model.dto.UserDTO;
import org.xjtu.weteam.service.UserTeamService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class UserTeamServiceImpl extends ServiceImpl<UserTeamMapper, UserTeam> implements UserTeamService {
    @Autowired
    private UserTeamMapper userTeamMapper;


    @Override
    public List<User> selectAllUsers(Integer teamid) {
        return userTeamMapper.selectAllUsers(teamid);
    }

    @Override
    public List<UserDTO> selectUsersWithAvatar(Integer teamId) throws IOException {
        List<User> users = this.selectAllUsers(teamId);
        List<UserDTO> userDTOS = new ArrayList<>();
        for (User user : users) {
            UserDTO userDTO = new UserDTO();
            userDTO.setUserId(user.getUserId()).setNickname(user.getNickname()).setImage(imageUtil.getAvatar(user.getImagePath()));
            userDTOS.add(userDTO);
        }
        return userDTOS;
    }

    @Override
    public void removeRelationship(Integer userId, Integer teamId) {
        userTeamMapper.removeRelationship(userId, teamId);
    }

    @Override
    public Boolean checkIfIn(Integer teamId, Integer userId) {
        List<UserTeam> userTeam = userTeamMapper.checkIfIn(teamId,userId);
        return userTeam != null && !userTeam.isEmpty();
    }

    @Override
    public Boolean ifCreator(Integer teamId, Integer userId) {
        List<UserTeam> userTeam = userTeamMapper.checkIfIn(teamId,userId);
        return userTeam != null && !userTeam.isEmpty() && Objects.equals(userTeam.get(0).getRole(), "130");
    }

    @Override
    public void changeCreator(Integer teamId, Integer userId) {
        userTeamMapper.updateCreator(teamId, userId);
    }
}
